from typing import List, Optional, Dict, Any
from pymongo.database import Database
from bson import ObjectId

class AnalysisCRUD:
    def __init__(self, db: Database):
        self.db = db

    async def find_all_events(self) -> List[Dict[str, Any]]:
        """获取所有事件"""
        events = list(self.db["events"].find())
        for event in events:
            event["_id"] = str(event["_id"])
        return events

    async def find_one_event(self,event_id: int):
        """获取一个事件"""
        event=self.db["events"].find_one({"id":event_id})
        #event["_id"] = str(event["_id"])  后续处理
        return event
    
    async def update_one_event(self,event_id: int,update_data: Dict[str, Any]):
        """更新一个事件"""
        result = self.db["events"].update_one({"id":event_id}, {"$set": update_data})
        return {"success": bool(result.modified_count)}
    async def find_comments_by_event_id(self, e_id: int) -> List[Dict[str, Any]]:
        """根据事件ID获取评论"""
        comments = list(self.db["comments"].find({"e_id": e_id}))
        for comment in comments:
            comment["_id"] = str(comment["_id"])
        return comments

    async def find_articles_by_event_id(self, e_id: int) -> List[Dict[str, Any]]:
        """根据事件ID获取文章"""
        articles = list(self.db["articles"].find({"e_id": e_id}))
        for article in articles:
            article["_id"] = str(article["_id"])
        return articles

    async def insert_one(self, collection: str, data: Dict[str, Any]) -> Dict[str, Any]:
        """插入单条数据"""
        result = self.db[collection].insert_one(data)
        return {"success": bool(result.inserted_id)}

    async def insert_many(self, collection: str, data: List[Dict[str, Any]]) -> Dict[str, Any]:
        """插入多条数据"""
        result = self.db[collection].insert_many(data)
        return {"success": bool(result.inserted_ids)}

    async def update_one(self, collection: str, query: Dict[str, Any], update_data: Dict[str, Any]) -> Dict[str, Any]:
        """更新单条数据"""
        result = self.db[collection].update_one(query, {"$set": update_data})
        return {"success": bool(result.modified_count)}

    async def delete_one(self, collection: str, query: Dict[str, Any]) -> Dict[str, Any]:
        """删除单条数据"""
        result = self.db[collection].delete_one(query)
        return {"success": bool(result.deleted_count)} 